import { useContext,createContext, useReducer, useEffect } from 'react'
import listReducer from '../reducers/list-reducer'
const ListContext = createContext();

export const useList = () => useContext(ListContext);

const initState = {
    list: [],
    loading: false
}

const ListProvider = ({children}) => {
    const [state, dispatch] = useReducer(listReducer, initState);
    const { loading } = state;
    useEffect(() => {
        dispatch({ type: 'set_loading', loading: true })
        setTimeout(() => {
            const list = [
                { id: 0, title: 'aaaaaa' },
                { id: 1, title: 'bbbbbb' },
                { id: 2, title: 'cccccc' },
            ]
            dispatch({ type: 'set_list', list })
            dispatch({ type: 'set_loading', loading: false })
        }, 2000)
    }, [])
     if(loading){
        return <div>loading...</div>
    }
    return (
        <ListContext.Provider value={{ state, dispatch }}>
            {children}
        </ListContext.Provider>
    )
}

export default ListProvider